<!--
 * @Description:
 * @Author:       zhengxu
 * @Date: 2021-11-08 09:15:58
 * @LastEditors:  zhengxu
 * @LastEditTime: 2021-11-09 09:12:02
-->
<template>
  <a-modal
    title="添加路线"
    :width="640"
    centered
    class="custom_dialog"
    :visible="visible"
    :ok-button-props="{ disabled: confirmDisabled }"
    @ok="onOkClick"
    @cancel="onCancelClick"
  >
    <a-form
      label-align="right"
      :model="formData"
      :rules="rulesRef"
      :label-col="{ style: { width: '110px' } }"
      :wrapper-col="{ style: { marginLeft: '42px' }, span: 16 }">
      <a-form-item
        label="路线名称"
        v-bind="validateInfos.name">
        <a-input
          v-model:value="formData.name"
          autocomplete="off"/>
      </a-form-item>
      <a-form-item
        label="选择文件"
        v-bind="validateInfos.fileName">
        <a-input-group compact>
          <a-input
            v-model:value="formData.fileName"
            autocomplete="off"
            style="width: 85%"
            placeholder="请选择文件"/>
          <a-upload
            class="file_upload_btn"
            :show-upload-list="false"
            :custom-request="customRequest"
            accept=".txt">
            <img
              class="file_upload_icon"
              src="@/assets/images/icon_import.png" >
            浏览
          </a-upload>
        </a-input-group>
      </a-form-item>
      <a-form-item
        label="路线方向"
        name="direction">
        <a-select
          v-model:value="formData.direction"
          :options="RouteDirectionList"
          placeholder="请选择路线方向"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, computed } from 'vue'
import { message, Form } from 'ant-design-vue'
import { RouteDirectionList } from '@/config/simulation'
import { service as request } from '@/api/request'

const props = defineProps({
  // 弹框开启状态
  visible: Boolean,
  // 导入文件地址
  importUrl: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['update:visible', 'onOk'])
const confirmDisabled = computed(() => {
  let { direction, fileName, name } = formData.value
  return direction === undefined || !fileName || !name
})
const formData = ref({ direction: undefined, fileName: undefined, name: undefined })
// 表单校验规则
const rulesRef = reactive({
  direction: [
    { required: true, message: '请选择路线方向' }
  ],
  fileName: [
    { required: true, message: '请导入文件' }
  ],
  name: [
    { required: true, message: '请输入路线名称' }
  ]
})
const { useForm } = Form
const { validate, validateInfos } = useForm(formData, rulesRef)
let File = null // 保存当前选择的file
/**
 * 重写a-upload的文件上传处理方式
 * 保存上传file，取消默认上传事件
 */
function customRequest (data) {
  const isLt2M = data.file.size > 1024 * 1024 * 2
  if (isLt2M) {
    message.error('文件大小超出限制，请选择2M内的文件')
    return
  }
  const fileName = data.file.name
  if (!fileName.endsWith('.txt')) {
    message.error('文件类型错误,目前只支持txt文件')
    return
  }
  formData.value.fileName = fileName
  File = data.file
}
/**
 * 上传文件，调用上传接口保存文件
 */
function importFile () {
  if (!props.importUrl) {
    message.error('文件导入请求地址异常')
    return
  }
  const uploadForm = new FormData()
  uploadForm.append('routeFile', File)
  // 上传接口
  request({
    url: `${props.importUrl}?direction=${formData.value.direction}&name=${formData.value.name}`,
    method: 'POST',
    data: uploadForm
  }).then(({ data, resCode, resMsg }) => {
    if (resCode === '00000') {
      message.success('路线添加成功')
      emit('onSuccess', data)
    } else {
      emit('onfail', data)
      message.error(resMsg)
    }
  })
}
/**
 * 点击确认按钮
 * 进行表单验证，验证成功后上传文件
 */
function onOkClick () {
  validate()
    .then(() => {
      importFile()
    })
    .catch(() => {
      message.warning('请检查表单')
    })
}
/**
 * 点击取消按钮，关闭弹框
 */
function onCancelClick () {
  emit('update:visible', false)
}
</script>
<style>
.file_upload_btn {
  width: 15%;
  line-height: 32px;
  text-align: center;
  background: #2071f5;
}
.file_upload_btn .file_upload_icon {
  vertical-align: middle;
}
.file_upload_btn .ant-upload {
  color: #fff;
}
</style>
